package com.ruoyi.system.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.domain.dto.OfflineDto;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import com.ruoyi.system.api.service.OfflineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OfflineServiceImpl implements OfflineService {

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    @Autowired
    private ServiceLogMapper serviceLogMapper;

    @Autowired
    private StInfoUpdateMapper stInfoUpdateMapper;

    @Autowired
    private CcService ccService;

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;


    @Override
    public String uploadOfflineData(List<OfflineDto> offlineDtoList) {
        StringBuffer sb = new StringBuffer();
        for (OfflineDto offlineDto : offlineDtoList) {
            ServiceNotice serviceNoticeSearch = serviceNoticeMapper.selectServiceNoticeById(offlineDto.getServiceNoticeId());
            if (!"2".equals(serviceNoticeSearch.getDelFlag())) {
                // 1、升级Case
                if (StringUtils.isNotEmpty(offlineDto.getNewInstSn())) {
                    if (!offlineDto.getNewInstSn().equals(offlineDto.getInstSn())) {

                        StInfoUpdate stInfoUpdate = new StInfoUpdate();
                        stInfoUpdate.setRemarks("原序列号：" + offlineDto.getInstSn() + "，新序列号：" + offlineDto.getNewInstSn());
                        stInfoUpdate.setEnginnerId(Long.parseLong(offlineDto.getFseId()));
                        stInfoUpdate.setServiceNo(offlineDto.getServiceNo());
                        stInfoUpdate.setDelFlag("0");
                        stInfoUpdate.setStatus(0L);
                        stInfoUpdate.setCreateTime(new Date());
                        stInfoUpdate.setParameter(offlineDto.getNewInstSn());
                        // 信息修改申请的类型 1核对序列号 2地址变更 等...
                        stInfoUpdate.setType("1");
                        stInfoUpdateMapper.insertStInfoUpdate(stInfoUpdate);

                        // 更改核对序列号状态为已核对
                        ServiceNotice serviceNotice = new ServiceNotice();
                        serviceNotice.setServiceNo(offlineDto.getServiceNo());
                        serviceNotice.setIsCheck("2");
                        serviceNoticeMapper.updateServiceNoticeByServiceNo(serviceNotice);


                        /** 调用CC端接口 2.16信息修改申请 */
                        JSONObject jsonObject = ccService.updateOrderInfo(offlineDto.getFseId(), offlineDto.getServiceNo(), stInfoUpdate.getRemarks());
                        if ("200".equals(jsonObject.getString("code"))) {
                            stInfoUpdate.setRequestId(Long.parseLong(jsonObject.getString("data")));
                            stInfoUpdateMapper.updateStInfoUpdate(stInfoUpdate);
                        }
                    }
                }


                // 2、保存签到签离数据
                PlanDetails planDetails = planDetailsMapper.selectStPlanDetailsById(offlineDto.getPlanId());
                planDetails.setSignIn(offlineDto.getSignIn());
                planDetails.setSignInTime(offlineDto.getSignInTime());
                planDetails.setSignInLon(offlineDto.getSignInLon());
                planDetails.setSignInLat(offlineDto.getSignInLat());
                planDetails.setSignOff(offlineDto.getSignOff());
                planDetails.setSignOffTime(offlineDto.getSignOffTime());
                planDetails.setSignOffLon(offlineDto.getSignOffLon());
                planDetails.setSignOffLat(offlineDto.getSignOffLat());
                planDetails.setUpdateTime(new Date());
                ServiceDetails serviceDetails = new ServiceDetails();
                // 已签到
                if ("1".equals(offlineDto.getSignIn())) {
                    planDetails.setState("2");
                    serviceDetails.setState(2L);
                }
                // 已签离
                if ("1".equals(offlineDto.getSignOff())) {
                    planDetails.setState("3");
                    serviceDetails.setState(3L);
                }
                if (StringUtils.isNotEmpty(offlineDto.getSignOff())) {
                    if (offlineDto.getEstimatedVisitingTime() != null) {
                        planDetails.setState("3");
                        serviceDetails.setState(3L);
                    } else {
                        planDetails.setState("4");
                        serviceDetails.setState(4L);
                    }
                }
                serviceDetails.setServiceNoticeId(planDetails.getServiceNoticeId());
                serviceDetails.setFseId(planDetails.getFseId());
                planDetailsMapper.updateMyPlanDetails(planDetails);
                serviceDetailsMapper.updateMyServiceDetails(serviceDetails);

                // 3、生成新的计划
                if (offlineDto.getEstimatedDepartureTime() != null && offlineDto.getEstimatedVisitingTime() != null) {
                    PlanDetails planDetailsNew = new PlanDetails();
                    planDetailsNew.setServiceNoticeId(offlineDto.getServiceNoticeId());
                    planDetailsNew.setServiceNo(offlineDto.getServiceNo());
                    planDetailsNew.setFseId(offlineDto.getFseId());
                    planDetailsNew.setFseName(offlineDto.getFseName());
                    planDetailsNew.setIsAccept("1");
                    planDetailsNew.setEstimatedDepartureTime(offlineDto.getEstimatedDepartureTime());
                    planDetailsNew.setEstimatedVisitingTime(offlineDto.getEstimatedVisitingTime());
                    planDetailsNew.setEstimatedWorkingHours(offlineDto.getEstimatedWorkingHours());
                    planDetailsNew.setState("1");
                    planDetailsNew.setCreateTime(new Date());
                    planDetailsNew.setAcceptTime(new Date());
                    PlanDetails planDetailsSearch = new PlanDetails();
                    planDetailsSearch.setServiceNo(offlineDto.getServiceNo());
                    planDetailsSearch.setFseId(offlineDto.getFseId());
                    planDetailsSearch.setIsAccept("1");
                    List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);

                    if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
                        if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
                            planDetailsNew.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
                        }
                    }


                    planDetailsNew.setDelFlag("0");
                    planDetailsMapper.insertStPlanDetails(planDetailsNew);
                }

                // 4、工作日志保存
                if (offlineDto.getStartTime() != null && offlineDto.getEndTime() != null && StringUtils.isNotEmpty(offlineDto.getWorkContent())) {
                    // 更新计划详情表
                    planDetails.setFillInLog("1");
                    planDetails.setFillInLogTime(offlineDto.getWorkLogCreateTime());
                    planDetailsMapper.updateMyPlanDetails(planDetails);

                    // 新增服务日志表
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:dd:mm");
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:dd");
                    ServiceLog serviceLog = new ServiceLog();
                    serviceLog.setServiceNoticeId(offlineDto.getServiceNoticeId());
                    serviceLog.setServiceNo(offlineDto.getServiceNo());
                    serviceLog.setFseId(offlineDto.getFseId());
                    serviceLog.setStPlanId(offlineDto.getPlanId());
                    //判断填写日志次数（先查询列表最近一次，隔天flag+1）
                    List<ServiceLog> logList = serviceLogMapper.selectServiceLogList(serviceLog);
                    if (logList.size() > 0) {
                        int day = DateUtils.caculateTotalTime(sdf.format(logList.get(0).getCreateTime()), sdf.format(new Date()));
                        if (day > 1) {
                            serviceLog.setFlag(logList.get(0).getFlag() + 1);
                        } else {
                            serviceLog.setFlag(logList.get(0).getFlag());
                        }
                    } else {
                        serviceLog.setFlag(1);
                    }
                    serviceLog.setDepartureTime(offlineDto.getDepartureTime());
                    serviceLog.setFseName(offlineDto.getFseName());
                    serviceLog.setAcceptTime(offlineDto.getAcceptTime());
                    serviceLog.setArriveTime(offlineDto.getSignInTime());
                    serviceLog.setStartTime(offlineDto.getStartTime());
                    serviceLog.setEndTime(offlineDto.getEndTime());
                    serviceLog.setWorkHour(offlineDto.getWorkHour());
                    serviceLog.setJourneyHour(offlineDto.getJourneyHour());
                    serviceLog.setWorkContent(offlineDto.getWorkContent());
                    serviceLog.setDelFlag("0");
                    serviceLog.setCreateTime(new Date());
                    serviceLogMapper.insertServiceLog(serviceLog);
                }
            } else {
                sb.append(offlineDto.getServiceNo() + ",");
            }
        }

        return sb.toString();
    }

    @Override
    public  ArrayList<String> uploadOfflineDataCheck(List<OfflineDto> offlineDtoList) {
        List<String> offLineDatas = new ArrayList<>();
        for (OfflineDto offlineDto : offlineDtoList) {
            ServiceNotice serviceNoticeSearch = serviceNoticeMapper.selectServiceNoticeById(offlineDto.getServiceNoticeId());
            if ("2".equals(serviceNoticeSearch.getDelFlag())) {
                offLineDatas.add(offlineDto.getServiceNoticeId().toString());
            }
        }
      return (ArrayList<String>) offLineDatas;
    }
}